-
在哪里获取
有三种方案
1.1. 通过自定义Controller基类
优点: 简单,统一 缺点: 需要集成基类, 如果出现原始提交数据无法映射到Action参数里的情况,无法获取原始映射数据。 `csharp public class BaseController : Controller {
public override void OnActionExecuting(ActionExecutingContext context) { base.OnActionExecuting(context);
var request = context.HttpContext.Request;
string url = request.GetDisplayUrl(); //using Microsoft.AspNetCore.Http.Extensions;
StringBuilder sb = new StringBuilder();
sb.AppendLine(url);
if (request.ContentType?.StartsWith("multipart/form-data;") == true)
{
sb.AppendLine("Form Parameters: ");
sb.AppendLine(JsonConvert.SerializeObject(request.Form));
}
if(context.ActionArguments.Count > 0)
{
sb.AppendLine("JSON Parameters: ");
sb.AppendLine(JsonConvert.SerializeObject(context.ActionArguments));
}
}
}
` 继承此基类的controller中,都可以获取和处理请求信息。
1.2. 通过FilterAttribute
优点:可定制性强 缺点:无法统一处理
1.3. 通过中间件
优点:可以统一处理,功能强 缺点:未分析 ` private string ReadBodyAsString(HttpRequest request) { var initialBody = request.Body; // Workaround
try
{
request.EnableRewind();
using (StreamReader reader = new StreamReader(request.Body))
{
string text = reader.ReadToEnd();
return text;
}
}
finally
{
// Workaround so MVC action will be able to read body as well
request.Body = initialBody;
}
return string.Empty;
}
`
- 获取core mvc请求的url
上面的代码已经展示了,需要引用 Microsoft.AspNetCore.Http.Extensions;
然后利用其中 HttpRequest 的扩展方法: GetDisplayUrl()