我有一个ASP.NET CORE WebApi项目,该项目的基本控制器类覆盖了 OnActionExecuting 方法以执行工作(本文无关紧要的工作)。
当我在本地运行时将触发OnActionExecuting方法(VS Pro 2017-本地主机-IIS Express),但是当我将具有相同代码的内部版本发布到服务器环境时将无法触发(Windows Server 2016 Standard-IIS 10.0.14393.0 )。
有什么想法为什么要在localhost上调用OnActionExecuting方法,而无法在运行IIS的远程主机上触发?
这是代码:
public abstract class BaseController : Controller
{
public override void OnActionExecuting(ActionExecutingContext actionExecutingContext)
{
//This method fires on localhost but not on remote server (IIS)
//call into base method
base.OnActionExecuting(actionExecutingContext);
//validate http context exists
if (HttpContext == null)
throw new Exception("The HttpContext should not be null.");
//do other work...
}
}
答案 0 :(得分:0)
问题不是由于actionfilters引起的,由于IIS express中的请求正文问题,我遇到了同样的问题。
before reading request body need to EnableBuffering and after that need add Body.Position = 0
Solution 1:
context.Request.EnableBuffering();
// Leave the body open so the next middleware can read it.
using (var reader = new StreamReader(
context.Request.Body,
encoding: Encoding.UTF8,
detectEncodingFromByteOrderMarks: false,
bufferSize: bufferSize,
leaveOpen: true))
{
var body = await reader.ReadToEndAsync();
// Do some processing with body…
// Reset the request body stream position so the next middleware can read it
context.Request.Body.Position = 0;
}
solution 2:
private async Task<string> FormatRequest(HttpRequest request)
{
request.EnableBuffering();
var requestBody = await ReadBodyFromPipeReader(request.BodyReader);
request.Body.Position = 0;
return requestBody;
}
private async Task<string> ReadBodyFromPipeReader(PipeReader reader)
{
StringBuilder stringBuilder = new StringBuilder();
while (true)
{
// await some data being available
ReadResult read = await reader.ReadAsync();
ReadOnlySequence<byte> buffer = read.Buffer;
// check whether we've reached the end
// and processed everything
if (buffer.IsEmpty && read.IsCompleted)
break; // exit loop
// process what we received
foreach (var segment in buffer)
{
string asciString = Encoding.ASCII.GetString(
segment.Span);
stringBuilder.Append(asciString);
}
// tell the pipe that we used everything
reader.AdvanceTo(buffer.Start, buffer.End);
if (read.IsCompleted)
{
break;
}
}
return Convert.ToString(stringBuilder);
}