加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何从asp.net处理程序返回404错误?

发布时间:2020-12-15 03:59:43 所属栏目:百科 来源:网络整理
导读:我创建了一个下载文件的处理程序. 如果文件不存在或用户无权下载该特定文件,我想返回404错误. 可能吗?如果是,怎么样?示例代码将不胜感激. 解决方法 检查此代码 public class MyHandler : IHttpHandler{ private const string CONSTSOMEPARAM = "SomeParam"
我创建了一个下载文件的处理程序.
如果文件不存在或用户无权下载该特定文件,我想返回404错误.

可能吗?如果是,怎么样?示例代码将不胜感激.

解决方法

检查此代码
public class MyHandler : IHttpHandler
{
    private const string CONSTSOMEPARAM = "SomeParam";

    public MyHandler() { }

    public void ProcessRequest(HttpContext context)
    {
        // Don't allow this response to be cached by the browser.
        // Note,you MIGHT want to allow it to be cached,depending on what you're doing.
        context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        context.Response.Cache.SetNoStore();
        context.Response.Cache.SetExpires(DateTime.MinValue);

        if (ValidateParameters(context) == false)
        {
            //Internal Server Error
            context.Response.StatusCode = 500;
            context.Response.End();
            return;
        }

        if (context.User.Identity.IsAuthenticated == false)
        {
            //Forbidden
            context.Response.StatusCode = 403;
            context.Response.End();
            return;
        }

        string someParam = context.Request.QueryString[CONSTSOMEPARAM];

        SomethingReponse response = SomeService.SomeImportantThing(someParam);
        if (response.Header == null || response.Header.Success == false)
        {
            //Whatever wasn't found
            context.Response.StatusCode = 404;
            context.Response.End();
            return;
        }

        context.Response.ContentType = "somespecific/mimetype";

        context.Response.BinaryWrite();
        //or
        context.Response.Write();
        //or
        context.Response.WriteFile();
        //or
        someImageStream.Save(context.Response.OutputStream);
    }

    public bool ValidateParameters(HttpContext context)
    {
        //Validate some stuff...true if cool,false if not
        return false;
    }

    /// <summary>
    /// True if this handler can be reused between calls. That's cool if you don't have any class instance data.
    /// False if you'd rather get a fresh one.
    /// </summary>
    public bool IsReusable
    {
        get
        {
            return true;
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读