question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

NsWag generated code for c# dose not match with response dto object

See original GitHub issue

I use blow code for get token in winform:

var tokenService = new Services.WebApi.TokenAuthClient("http://localhost:21021");
var result = await tokenService.AuthenticateAsync(new Services.WebApi.AuthenticateModel()
{
    UserNameOrEmailAddress = "admin",
    Password = "123qwe",
    RememberClient = true
});

The service class generated via Nswag. but problem where blow method want deserialize json response to AuthenticateResultModel and it not work.

public async System.Threading.Tasks.Task<AuthenticateResultModel> AuthenticateAsync(AuthenticateModel model, System.Threading.CancellationToken cancellationToken)
{
...
      result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<AuthenticateResultModel>(responseData_ , _settings.Value);
....
}

deserializer not work because response template do not match with AuthenticateResultModel Response:

{
    "result":
    {
    "accessToken":"5",
    "encryptedAccessToken":"6",
    "expireInSeconds":86400,
    "userId":2
    },
"targetUrl":null,
"success":true,
"error":null,
"unAuthorizedRequest":false,
"__abp":true
}

But AuthenticateResultModel:

[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "9.6.5.0 (Newtonsoft.Json v9.0.0.0)")]
public partial class AuthenticateResultModel 
{
    [Newtonsoft.Json.JsonProperty("accessToken", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
    public string AccessToken { get; set; }
    
    [Newtonsoft.Json.JsonProperty("encryptedAccessToken", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
    public string EncryptedAccessToken { get; set; }
    
    [Newtonsoft.Json.JsonProperty("expireInSeconds", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
    public int? ExpireInSeconds { get; set; }
    
    [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
    public long? UserId { get; set; }
    
    public string ToJson() 
    {
        return Newtonsoft.Json.JsonConvert.SerializeObject(this);
    }
        
    public static AuthenticateResultModel FromJson(string data)
    {
        return Newtonsoft.Json.JsonConvert.DeserializeObject<AuthenticateResultModel>(data);
    }
}

I test with new model class and it work how configure Nswag or Abp to generate correct code?

public class AuthenticateResultModel
{
    public AuthenticateResultModel Result{ get; set; }
    public string TargetUrl { get; set; }
    public bool Success { get; set; }
    public string Error { get; set; }
    public bool UnAuthorizedRequest { get; set; }
    public bool __abp { get; set; }
}

public class AuthenticateResultModel
{
    public string AccessToken { get; set; }
    public string EncryptedAccessToken { get; set; }
    public int? ExpireInSeconds { get; set; }
    public long? UserId { get; set; }
}

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
jogoertzen-stanteccommented, Nov 26, 2018

@ismcagdas as for response from Nswag owner, i can add attribute to controller methods, but in abp controllers generated dynamicly (Application Services as Controllers). How i can add this attribute to controller methods? Of course, there is another solution (implement a custom OperationProcessor …)

Attribute for controller methods [SwaggerResponse(200, typeof(MyResponse)]

public class MyResponse<T>
{
    public T Result { get; set; }
    public string TargetUrl { get; set; }
    public bool Success { get; set; }
    public string Error { get; set; }
    public bool UnAuthorizedRequest { get; set; }
    public bool __abp { get; set; }
}

This worked for me, but I used

[ProducesResponseType(typeof(MyResponse<...>), 200)]

instead of

[SwaggerResponse(200, typeof(MyResponse<...>)]

as per this

0reactions
Rgl88commented, Oct 8, 2017

Very simple solution:

var str = File.ReadAllText(filePath);

var methodReturnPattern = @"System.Threading.Tasks.Task<(?'TypeName'\w+){1}\>+";

var deserializerPattern = @"result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<(?'TypeName'\w+){1}\>{1}";

var resultDefinitionPattern = @"default\((?'TypeName'\w+){1}\);{1}";

var baseUrlPattern = @"(?'VarName'urlBuilder_)\.Append";

var result = Regex.Replace(str, methodReturnPattern, m => m.Value.Replace(m.Groups["TypeName"].Value, "Response<"+m.Groups["TypeName"].Value + ">"));
result = Regex.Replace(result, deserializerPattern, m => m.Value.Replace(m.Groups["TypeName"].Value, "Response<" + m.Groups["TypeName"].Value + ">"));
result = Regex.Replace(result, resultDefinitionPattern, m => m.Value.Replace(m.Groups["TypeName"].Value, "Response<" + m.Groups["TypeName"].Value + ">"));
result = Regex.Replace(result, baseUrlPattern, m => m.Value.Replace(m.Groups["VarName"].Value, m.Groups["VarName"].Value + ".Append(BaseUrl)"));
File.WriteAllText(filePath, result);
Read more comments on GitHub >

github_iconTop Results From Across the Web

How do I customise the generated DTO for the C# Client in ...
NET's HttpClient but I'd like to use NSwagStudio's code generator to generate code that calls my generic client rather than the standard ...
Read more >
Whats your preferred way to create a typed C# client from ...
NSwag provides a host of really good options for generating clients from swagger docs. This is what we use for a similar case...
Read more >
Generate C# client for OpenAPI - Kaylumah
So I needed a type-safe client for use in my C# code base. ... the name of the MSBuild variable does not need...
Read more >
Get started with NSwag and ASP.NET Core
Learn how to use NSwag to generate documentation and help pages for an ASP.NET Core web API.
Read more >
Generate TypeScript and C# clients with NSwag based on ...
Learn how to generate TypeScript and C# API clients with NSwag to reduce your workload when building a project.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found