简体   繁体   English

C#Webmethod + jQuery发布错误消息

[英]C# Webmethod + Jquery post error message

I am trying to throw a handled exception through JQuery Post and a Webmethod so that I can get an error message back to the alert function. 我正在尝试通过JQuery Post和Webmethod抛出处理后的异常,以便可以将错误消息返回到警报功能。 So this is just a test script. 因此,这只是一个测试脚本。

I have this set up, and am catching the error, now I need to return the server error back to the alert function! 我已经设置好了,并且正在捕获错误,现在我需要将服务器错误返回到警报功能!

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string Test()
{
    try
    {
        string value = null;
        if (value.Length == 0) // <-- Causes exception
        {
            Console.WriteLine(value); // <-- Never reached
        }

    }

    catch (Exception E)
    {            

        StreamWriter sw = new StreamWriter(@"C:\inetpub\wwwroot\jQuery_AJAX_Database\error.txt", true);
        sw.WriteLine(E.Message);

        sw.Close();
        sw.Dispose();

        throw new Exception("error");

    }

    return "bla";

And this my Post script: 这是我的Post脚本:

 $("#btnTest").click(function () {
            $.ajax({
                type: 'POST',
                url: "my_test2.aspx/Test",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    alert('Success!')
                },
                error: function (xhr, status, error) {
                    var exception = JSON.parse(xhr.responseText);
                    alert(exception.Message);
                    // Here I need to return server error
                }
            });
        });

Thanks P 谢谢P

You need an http status code to do that. 您需要一个http状态代码来执行此操作。

Modify your code into this 修改您的代码

catch (Exception E)
    {            

        StreamWriter sw = new StreamWriter(@"C:\inetpub\wwwroot\jQuery_AJAX_Database\error.txt", true);
        sw.WriteLine(E.Message);

        sw.Close();
        sw.Dispose();

        return new HttpStatusCodeResult(500, E.Message);
    }

500 stands for internal server error . 500代表internal server error have a look for another if it fits better. 如果合适的话,再找一个。

I think 400 - Bad Request might be more suited for your situation. 我认为400 - Bad Request可能更适合您的情况。

Thanks @ted you got me on the right track. 谢谢@ted,让我步入正轨。 Solved as below! 解决如下!

throw new HttpException(E.Message);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM