2012-05-15 34 views
5

Tôi có một phương pháp web, được gọi là từ phương pháp ajax jquery của, như thế này:Làm thế nào để đăng nhập yêu cầu JSON các dịch vụ web

$.ajax({ 
    type: "POST", 
    url: "MyWebService.aspx/DoSomething", 
    data: '{"myClass": ' + JSON.stringify(myClass) + '}', 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    async: false, 
    success: function (result) { 
     alert("success"); 
    }, 
    error: function() { 
     alert("error"); 
    } 
}); 

Và đây là phương pháp web của tôi:

[WebMethod(EnableSession = true)] 
public static object DoSomething(MyClass myClass) 
{ 
    HttpContext.Current.Request.InputStream.Position = 0; 
    using (var reader = new StreamReader(HttpContext.Current.Request.InputStream)) 
    { 
    Logger.Log(reader.ReadToEnd()); 
    } 
} 

Nếu myClass trong javascript được tuần tự hóa để định dạng đúng, sau đó các phương thức DoSomething thực hiện và lưu json thô vào cơ sở dữ liệu. Nhưng nếu myClass bị sai thì phương thức đó không thực thi và tôi không thể ghi nhật ký json có vấn đề ...

Cách tốt nhất để luôn lấy được và ghi nhật ký json thô là trang web của tôi là gì phương pháp nhận được, ngay cả khi serialization không?

+1

Try googling "IIS log yêu cầu HttpModule" bạn nên tìm một cái gì đó hữu ích (xin lỗi tôi không thể tìm thấy mã có liên quan ngay bây giờ) – Alex

+0

@alex - cảm ơn, IHttpModule chính xác là những gì tôi cần. – sventevit

Trả lời

1

Với sự giúp đỡ của một số câu trả lời khác trên stackoverflow tôi đến đây:

public class RequestLogModule : IHttpModule 
{ 
    private HttpApplication _application; 

    public void Dispose() 
    { 
    } 

    public void Init(HttpApplication context) 
    { 
     _application = context; 
     _application.BeginRequest += ContextBeginRequest; 
    } 

    private void ContextBeginRequest(object sender, EventArgs e) 
    { 
     var request = _application.Request; 

     var bytes = new byte[request.InputStream.Length]; 
     request.InputStream.Read(bytes, 0, bytes.Length); 
     request.InputStream.Position = 0; 
     string content = Encoding.UTF8.GetString(bytes); 

     Logger.LogRequest(
      request.UrlReferrer == null ? "" : request.UrlReferrer.AbsoluteUri, 
      request.Url.AbsoluteUri, 
      request.UserAgent, 
      request.UserHostAddress, 
      request.UserHostName, 
      request.UserLanguages == null ? "" : request.UserLanguages.Aggregate((a, b) => a + "," + b), 
      request.ContentType, 
      request.HttpMethod, 
      content 
     ); 
    } 
} 

Và trong web.config:

<httpModules> 
    <add name="MyRequestLogModule" type="MyNamespace.RequestLogModule, MyAssembly"/> 
</httpModules> 
-3

Bạn luôn có thể làm điều đó ở phía máy chủ.

khi bạn gửi yêu cầu tới "MyWebService.aspx/DoSomething" gọi dịch vụ web, bạn có thể ghi kết quả (thành công/lỗi) vào tệp nhật ký.

Các vấn đề liên quan