GVKun编程网logo

c# – Response.Flush()抛出System.Web.HttpException(c#抛出异常出错)

38

本文将为您提供关于c#–Response.Flush()抛出System.Web.HttpException的详细介绍,我们还将为您解释c#抛出异常出错的相关知识,同时,我们还将为您提供关于ABP:F

本文将为您提供关于c# – Response.Flush()抛出System.Web.HttpException的详细介绍,我们还将为您解释c#抛出异常出错的相关知识,同时,我们还将为您提供关于ABP:FlurlHttpException涵盖了UserFriendlyException、ASP.NET Core 中的 DbContext 抛出 System.ObjectDisposedException、ASP.NET Web Api HttpResponseException 400(错误请求)被IIS劫持、asp.net – Googlebot导致.NET System.Web.HttpException的实用信息。

本文目录一览:

c# – Response.Flush()抛出System.Web.HttpException(c#抛出异常出错)

c# – Response.Flush()抛出System.Web.HttpException(c#抛出异常出错)

我有一个HttpHandler,我用来处理客户网站上的某些图像.当我将图像流输出到响应对象时,偶尔会调用Flush会抛出错误.这是一个代码块
var image = Image.FromStream(memStream);
if (size > -1) image = ImageResize.ResizeImage(image,size,false);
if (height > -1) image = ImageResize.Crop(image,height,ImageResize.AnchorPosition.Center);

context.Response.Clear();
context.Response.ContentType = contentType;
context.Response.BufferOutput = true;

image.Save(context.Response.OutputStream,ImageFormat.Jpeg);

context.Response.Flush();
context.Response.End();

从我读过的内容中,这个异常是由客户端在进程完成之前断开连接而导致的,没有任何冲突.

这是我的错误页面的输出

System.Web.HttpException: An error occurred while communicating with the remote host. The error code is 0x80070057.
Generated: Mon,12 Oct 2009 03:18:24 GMT

System.Web.HttpException: An error occurred while communicating with the remote host. The error code is 0x80070057.
   at System.Web.Hosting.ISAPIWorkerRequestInProcForIIS6.FlushCore(Byte[] status,Byte[] header,Int32 keepConnected,Int32 totalBodySize,Int32 numBodyFragments,IntPtr[] bodyFragments,Int32[] bodyFragmentLengths,Int32 doneWithSession,Int32 finalStatus,Boolean& async)
   at System.Web.Hosting.ISAPIWorkerRequest.FlushCachedResponse(Boolean isFinal)
   at System.Web.Hosting.ISAPIWorkerRequest.FlushResponse(Boolean finalFlush)
   at System.Web.HttpResponse.Flush(Boolean finalFlush)
   at System.Web.HttpResponse.Flush()
   at PineBluff.Core.ImageHandler.ProcessRequest(HttpContext context) in c:\TeamCity\buildAgent\work\79b3c57a060ff42d\src\PineBluff.Core\ImageHandler.cs:line 75
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean& completedSynchronously)

context.Response.Flush属于第75行.

在执行flush之前,是否有一种检查方法,而不会将其包装在try / catch块中.

解决方法

虽然我同意 Mitchel – 如果您在其他地方使用此功能,您可以先尝试致电 Response.IsClientConnnected.

Gets a value indicating whether the client is still connected to the server.

ABP:FlurlHttpException涵盖了UserFriendlyException

ABP:FlurlHttpException涵盖了UserFriendlyException

dynamic d = ex.GetResponseJson();做到了。

谢谢

ASP.NET Core 中的 DbContext 抛出 System.ObjectDisposedException

ASP.NET Core 中的 DbContext 抛出 System.ObjectDisposedException

如何解决ASP.NET Core 中的 DbContext 抛出 System.ObjectDisposedException?

我正在 ASP.NET Core 应用程序中使用 EF Core 将 Todo 模型保存到数据库。 但是当我尝试使用 Console.Writeline 打印成功消息时,它会抛出 System.ObjectdisposedException

这是完整的应用程序 github code link

这是 Todo 模型:

public class Todo
{
    public int Id { get; set; }

    [required]
    [MaxLength(10)]
    public string Title { get; set; }

    public bool IsCompleted { get; set; } = false;
}

这里是抛出异常的业务逻辑。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TodoApp.Models;
using TodoApp.Data;

namespace TodoApp
{
    public class TodoService
    {
        readonly TodoContext _context;

        public TodoService(TodoContext context)
        {
            _context = context;
        }

        public async Task<int> CreatetoDo(CreatetodobindingModel input)
        {
            Todo todo = new()
            {
                Title = input.Title,IsCompleted = input.IsCompleted
            };

            _context.Add(todo);
            await _context.SaveChangesAsync();
            Console.WriteLine("Successfully saved todo.");
            return task.Id;
        }
    }
}

异常详情:

System.ObjectdisposedException
  HResult=0x80131622
  Message=Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling ''dispose'' on the context instance,or wrapping it in a using statement. If you are using dependency injection,you should let the dependency injection container take care of disposing context instances.
Object name: ''TodoContext''.
  Source=Microsoft.EntityFrameworkCore
  StackTrace:
   at Microsoft.EntityFrameworkCore.DbContext.Checkdisposed()

Console.Writeline 为什么会抛出异常?

编辑: 这是 TodoContext:

    public class TodoContext: DbContext
    {
        public TodoContext(DbContextOptions<TodoContext> options)
        : base(options)
        { }

        public DbSet<Todo> Todos { get; set; }
    }

以下是它在 Startup.cs 中的注册方式:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();

            var connectionString = Configuration["ConnectionString"];
            services.AddDbContext<TodoContext>(options => options.UseNpgsql(connectionString));

            services.AddScoped<TodoService>();
        }

这是完整的应用程序 github code link

解决方法

问题出在您代码的这一部分:

 public IActionResult OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }
            Task<int> id =  _service.CreateTask(Input);//<--- this line
            return RedirectToPage("Index");
        }

调用返回任务后的 createTask 意味着尚未完成并且您不等待它完成,当调用 RedirectToPage 当前请求完成时。因为您的服务和 dbcontext 以 Scope 生命周期添加到 DI,这意味着对象的生命周期在请求期间,当请求完成时,该对象将被处理。

所以解决问题就用这种方式:

 public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }
            int id = await _service.CreateTask(Input);
            return RedirectToPage("Index");
        }

ASP.NET Web Api HttpResponseException 400(错误请求)被IIS劫持

ASP.NET Web Api HttpResponseException 400(错误请求)被IIS劫持

如果我的ModelState无效,我正在编写一个Web API服务并尝试返回(400)错误请求.我不想要一个响应机构附加到这个.看来,IIS正在劫持我的响应,并且始终返回一个文本/ html内容类型与一个冗长的风格的错误页面.这是个问题.
[HttpPost]
    public void Link(LinkDeviceModel model)
    {

        if (ModelState.IsValid)
        {
            try
            {
                model.Save();
            }
            catch (Exception ex)
            {
                ErrorSignal.FromCurrentContext().Raise(ex);
                throw new HttpResponseException(ex.Message,HttpStatusCode.InternalServerError);
            }
        }
        else
        {
            throw new HttpResponseException(HttpStatusCode.BadRequest);
        }
    }

这是我的提示请求:

POST http://localhost/myapp/service/link HTTP/1.1
Host: localhost
Content-Length: 112
Content-Type: application/json
Accept: application/json

{"DeviceUniqueId":"CC9C6FC0-7D06-11E1-8B0E-31564824019B","UserName": "me@mycompany.com"," Pin": "111111"}

而我的回答错误,充满了身体,回应:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title>IIS 7.5 Detailed Error - 400.0 - Bad Request</title> 
<style type="text/css"> 
<!-- 
body{margin:0;font-size:.7em;font-family:Verdana,Arial,Helvetica,sans-serif;background:#CBE1EF;} 
code{margin:0;color:#006600;font-size:1.1em;font-weight:bold;} 
.config_source code{font-size:.8em;color:#000000;} 
pre{margin:0;font-size:1.4em;word-wrap:break-word;} 
ul,ol{margin:10px 0 10px 40px;} 
ul.first,ol.first{margin-top:5px;} 
fieldset{padding:0 15px 10px 15px;} 
.summary-container fieldset{padding-bottom:5px;margin-top:4px;} 
legend.no-expand-all{padding:2px 15px 4px 10px;margin:0 0 0 -12px;} 
legend{color:#333333;padding:4px 15px 4px 10px;margin:4px 0 8px -12px;_margin-top:0px; 
 border-top:1px solid #EDEDED;border-left:1px solid #EDEDED;border-right:1px solid #969696; 
 border-bottom:1px solid #969696;background:#E7ECF0;font-weight:bold;font-size:1em;} 
a:link,a:visited{color:#007EFF;font-weight:bold;} 
a:hover{text-decoration:none;} 
h1{font-size:2.4em;margin:0;color:#FFF;} 
h2{font-size:1.7em;margin:0;color:#CC0000;} 
h3{font-size:1.4em;margin:10px 0 0 0;color:#CC0000;} 
h4{font-size:1.2em;margin:10px 0 5px 0; 
}#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS",Verdana,sans-serif; 
 color:#FFF;background-color:#5C87B2; 
}#content{margin:0 0 0 2%;position:relative;} 
.summary-container,.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;} 
.config_source{background:#fff5c4;} 
.content-container p{margin:0 0 10px 0; 
}#details-left{width:35%;float:left;margin-right:2%; 
}#details-right{width:63%;float:left;overflow:hidden; 
}#server_version{width:96%;_height:1px;min-height:1px;margin:0 0 5px 0;padding:11px 2% 8px 2%;color:#FFFFFF; 
 background-color:#5A7FA5;border-bottom:1px solid #C1CFDD;border-top:1px solid #4A6C8E;font-weight:normal; 
 font-size:1em;color:#FFF;text-align:right; 
}#server_version p{margin:5px 0;} 
table{margin:4px 0 4px 0;width:100%;border:none;} 
td,th{vertical-align:top;padding:3px 0;text-align:left;font-weight:bold;border:none;} 
th{width:30%;text-align:right;padding-right:2%;font-weight:normal;} 
thead th{background-color:#ebebeb;width:25%; 
}#details-right th{width:20%;} 
table tr.alt td,table tr.alt th{background-color:#ebebeb;} 
.highlight-code{color:#CC0000;font-weight:bold;font-style:italic;} 
.clear{clear:both;} 
.preferred{padding:0 5px 2px 5px;font-weight:normal;background:#006633;color:#FFF;font-size:.8em;} 
--> 
</style> 

</head> 
<body> 
<div id="header"><h1>Server Error in Application "DEFAULT WEB SITE/MYAPP"</h1></div> 
<div id="server_version"><p>Internet information Services 7.5</p></div> 
<div id="content"> 
<div> 
 <fieldset><legend>Error Summary</legend> 
  <h2>HTTP Error 400.0 - Bad Request</h2> 
  <h3>Bad Request</h3> 
 </fieldset> 
</div> 
<div> 
 <fieldset><legend>Detailed Error information</legend> 
  <div id="details-left"> 
   <table border="0" cellpadding="0" cellspacing="0"> 
    <tr><th>Module</th><td>ManagedPipelineHandler</td></tr> 
    <tr><th>Notification</th><td>ExecuteRequestHandler</td></tr> 
    <tr><th>Handler</th><td>System.Web.Http.WebHost.HttpControllerHandler</td></tr> 
    <tr><th>Error Code</th><td>0x00000000</td></tr> 

   </table> 
  </div> 
  <div id="details-right"> 
   <table border="0" cellpadding="0" cellspacing="0"> 
    <tr><th>Requested URL</th><td>http://localhost:80/myapp/service/link</td></tr> 
    <tr><th>Physical Path</th><td>C:\workspace\myapp\service\link</td></tr> 
    <tr><th>logon Method</th><td>Anonymous</td></tr> 
    <tr><th>logon User</th><td>Anonymous</td></tr> 

   </table> 
   <div></div> 
  </div> 
 </fieldset> 
</div> 
<div> 
 <fieldset><legend>Most likely causes:</legend> 
  <ul>  <li></li> </ul> 
 </fieldset> 
</div> 
<div> 
 <fieldset><legend>Things you can try:</legend> 
  <ul>  <li>Create a tracing rule to track Failed requests for this HTTP status code. For more information about creating a tracing rule for Failed requests,click <a href="http://go.microsoft.com/fwlink/?LinkID=66439">here</a>. </li> </ul> 
 </fieldset> 
</div> 


<div> 
 <fieldset><legend>Links and More information</legend> 
  The request Could not be understood by the server due to malformed Syntax. 
  <p><a href="http://go.microsoft.com/fwlink/?LinkID=62293&amp;IIS70Error=400,0x00000000,7601">View more information &raquo;</a></p> 
  <p>Microsoft KNowledge Base Articles:</p> 
 <ul><li></li></ul> 

 </fieldset> 
</div> 
</div> 
</body> 
</html>

我试图设置TrySkipIisCustomErrors = True有很大的希望,但没有运气.有任何想法吗?赞赏.谢谢.

解决方法

尝试将其添加到您的web.config.我有一个非常类似的问题,这解决了.
<configuration>
<system.webServer>
<httpErrors existingResponse="Passthrough" />
</system.webServer>
</configuration>

asp.net – Googlebot导致.NET System.Web.HttpException

asp.net – Googlebot导致.NET System.Web.HttpException

我有一个ASP.NET网站混合了经典的asp(我们正在转换到.NET),我最近从.NET 1.1升级到.NET 4.0,并在IIS 7中切换到集成管道.

由于这些变化,ELMAH从传统的asp页面报告错误,实际上没有细节(和状态代码404):

System.Web.HttpException (0x80004005)
   at System.Web.CachedpathData.ValidatePath(String physicalPath)
   at System.Web.HttpApplication.PipelinestepManager.ValidateHelper(HttpContext context)

但是当我自己请求页面时,不会发生错误.所有出现在ELMAH中的错误都是由Googlebot抓取工具(用户代理字符串)引起的.

.NET如何为传统的asp页面挑选错误?这与集成管道有关吗?

任何想法,为什么错误只发生在Google抓取页面或如何获得更多的细节来找到潜在的错误?

解决方法

将其添加到您的web.config文件中:
<httpRuntime relaxedUrlToFileSystemMapping="true" />

此disables the default check确保所请求的URL符合Windows路径规则.

要重现问题,请将(URL转义的空格)添加到URL的末尾,例如http://example.org/.当搜索抓取工具遇到带有空格的错误类型的链接时,这是很常见的. < a href =“http://example.org/”>示例< / a&gt ;. HttpContext.Request.Url属性似乎修剪了尾随空间,这就是为什么像ELMAH这样的日志记录工具不会揭示实际的问题.

关于c# – Response.Flush()抛出System.Web.HttpExceptionc#抛出异常出错的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于ABP:FlurlHttpException涵盖了UserFriendlyException、ASP.NET Core 中的 DbContext 抛出 System.ObjectDisposedException、ASP.NET Web Api HttpResponseException 400(错误请求)被IIS劫持、asp.net – Googlebot导致.NET System.Web.HttpException的相关知识,请在本站寻找。

本文标签: